const httpUrl = getApp().globalData.httpUrl;

const hideLoading = () =>{
  return new Promise((resolve, reject) => {
    wx.hideLoading({
      success: () =>{
        resolve(true); // 成功关闭loading，返回true
      },
      fail: () =>{
        reject(false); // 关闭loading失败，返回false
      }
    });
  });
};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    result:[],
    shopList:[],
    addressId: '',
    addressList:[],
    addressName:'',
    phone:'',
    address:'',
    Allprice:0,
    Allnum:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that =this;
    this.setData({
      result:JSON.parse(options.result),
      shopList:JSON.parse(options.shopList)
    },()=>{
      this.getAddressList();
      var num = 0;
      var price = 0;
      for (let index = 0; index < this.data.shopList.length; index++) {
        num += this.data.shopList[index].num;
        price += this.data.shopList[index].num * this.data.shopList[index].price 
      }
      that.setData({
        Allnum:num,
        Allprice:price
      })
    })
  },
  onChange(event) {
    this.setData({
      addressId: event.detail,
    });
  },
  gotoInput(){
    wx.navigateTo({
      url: '/pages/input/input',
    })
  },

  getAddressList(){
    var that = this;
    wx.request({
      url: httpUrl + '/address',
      method:'GET',
      header:{
        'Shop_token':wx.getStorageSync('Shop_token')
      },
      success(res){
        if (res.data.code == 20041) {
          that.setData({
            addressList:res.data.data.rows,
            addressTotal:res.data.data.totalCount
          })
        }
        else if (res.data.code == 401) {
          console.log(res.data.msg);
          wx.removeStorageSync('Shop_token');
          wx.navigateTo({
            url: '/pages/login/login',
          })
        }
        else if (res.data.code == 402) {
          console.log(res.data.msg);
          // wx.removeStorageSync('Shop_token');
          wx.navigateTo({
            url: '/pages/login/login',
          })
        }
        else{
          console.log(res.data.msg);
        }
      },
      fail(err){
        console.log(err);
      }
    })
  },

  buy(){
    var that = this;
    if (this.data.addressId=='') {
      wx.showToast({
        title: '请选择地址',
        icon:'error'
      })
    }else{
      for (let j = 0; j < that.data.shopList.length; j++) {
        var shopId = that.data.shopList[j].shopId;
        wx.request({
          url: httpUrl + '/shop/count/' + shopId,
          method:'GET',
          header:{
            'Shop_token':wx.getStorageSync('Shop_token')
          },
          success(res){
            if (res.data.code == 20041) {
              if (res.data.data < that.data.shopList[j].num) {
                wx.showToast({
                  mask:true,
                  title: that.data.shopList[j].shopName+'库存不足,'+ '现在购买下一个物品',
                  icon:'none',
                  duration:1500
                })
              }else{
                wx.request({
                  url: httpUrl + '/address/' + that.data.addressId,
                  method:'GET',
                  header:{
                    'Shop_token':wx.getStorageSync('Shop_token')
                  },
                  success(res){
                    if (res.data.code == 20041) {
                      that.setData({
                        addressName:res.data.data.name,
                        phone:res.data.data.phone,
                        address:res.data.data.address
                      },()=>{
                        var date = new Date().getTime();
                        wx.request({
                          url: httpUrl + '/order',
                          method:'POST',
                          header:{
                            'Shop_token':wx.getStorageSync('Shop_token')
                          },
                          data:{
                            count:that.data.shopList[j].num,
                            price:that.data.shopList[j].price * that.data.shopList[j].num,
                            shopId:that.data.shopList[j].shopId,
                            addressName:that.data.addressName,
                            phone:that.data.phone,
                            address:that.data.address,
                            date:date
                          },
                          success(res){
                            if (res.data.code == 20011) {
                              wx.showToast({
                                title: '支付成功',
                                icon:'success'
                              });
                              setTimeout(function() {
                                wx.navigateBack({
                                  delta: 1
                                });
                              }, 300);
                            }
                            else if (res.data.code == 401) {
                              console.log(res.data.msg);
                              wx.removeStorageSync('Shop_token');
                              wx.navigateTo({
                                url: '/pages/login/login',
                              })
                            }
                            else if (res.data.code == 402) {
                              console.log(res.data.msg);
                              // wx.removeStorageSync('Shop_token');
                              wx.navigateTo({
                                url: '/pages/login/login',
                              })
                            }
                            else{
                              console.log(res.data.msg);
                            }
                          },
                          fail(err){
                            console.log(err);
                          }
                        })
                      })
                    }
                    else if (res.data.code == 401) {
                      console.log(res.data.msg);
                      wx.removeStorageSync('Shop_token');
                      wx.navigateTo({
                        url: '/pages/login/login',
                      })
                    }
                    else if (res.data.code == 402) {
                      console.log(res.data.msg);
                      // wx.removeStorageSync('Shop_token');
                      wx.navigateTo({
                        url: '/pages/login/login',
                      })
                    }
                    else{
                      console.log(res.data.msg);
                    }
                  },
                  fail(err){
                    console.log(err);
                  }
                })
              }
            }
            else if (res.data.code == 401) {
              console.log(res.data.msg);
              wx.removeStorageSync('Shop_token');
              wx.navigateTo({
                url: '/pages/login/login',
              })
            }
            else if (res.data.code == 402) {
              console.log(res.data.msg);
              // wx.removeStorageSync('Shop_token');
              wx.navigateTo({
                url: '/pages/login/login',
              })
            }
            else{
              console.log(res.data.msg);
            }
          },
          fail(err){
            console.log(err);
          }
        })
        
      }


    }
  },

  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})